package org.rc.web;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rc.loader.LoaderException;
import org.rc.loader.ResultsFileLoader;
import org.rc.model.ResultsFile;
import org.rc.parsing.StandardFormatParser;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

/**
 * This servlet will be responsible for uploading a file of results and store in the blobstore and associated metadata in the datastore.
 * This will not process the results. That will be done on a TaskQueue
 * @author dokeeffe
 */
public class ParseServlet extends IndexServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(ParseServlet.class);

    /**
     * Parse the file of results
     * FIXME: secure this action
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter("id") != null) {
            Long id= new Long(request.getParameter("id"));
            Long from= new Long(request.getParameter("from"));
            String retryStr = request.getParameter("retry");
            Integer retry = new Integer(0);
            if(retryStr!=null) {
                retry= new Integer(request.getParameter("retry"));    
            }
            Objectify ofy = ObjectifyService.begin();
            ResultsFile rf = ofy.get(ResultsFile.class,id);
            ResultsFileLoader loader = new ResultsFileLoader();
            try {
                loader.loadResults(rf, new StandardFormatParser(), from, retry);
            } catch (LoaderException ex) {
                LOGGER.error("error loading",ex);
                request.setAttribute("errors", "Error parsing " + ex.getMessage());
            }
        }
        forward(request, response, "upload.jsp");
    }
}
